package com.yc154.vote.controller;

import com.yc.starter.login.LoginProperties;
import com.yc154.vote.entity.Record;
import com.yc154.vote.entity.Result;
import com.yc154.vote.entity.User;
import com.yc154.vote.service.BizException;
import com.yc154.vote.service.IRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiaoYan
 * @since 2025-09-20
 */
@RestController
@RequestMapping("record")
public class RecordController {
    @Autowired
    LoginProperties loginProperties;

    @Autowired
    IRecordService recordService;

    @RequestMapping("vote")
    public Result vote(@RequestBody List<Record> records,
                       HttpSession session) {
        String sessionKey = loginProperties.getSessionKey();
        User myinfo = (User) session.getAttribute(sessionKey);
        if(myinfo == null){
            throw new BizException("请先登录系统", null);
        }
        if (records == null || records.isEmpty()) {
            throw new BizException("请选择投票的选项", null);
        }
        for (Record record : records) {
            record.setUsid(myinfo.getId());
            recordService.save(record);
        }
        return Result.ok("投票成功", null);
    }

}
